package com.jijuxie.system.service.impl;

import java.time.LocalDateTime;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jijuxie.system.domain.SysMessage;
import com.jijuxie.system.mapper.SysMessageMapper;
import com.jijuxie.system.service.ISysMessageService;

@Service
public class SysMessageServiceImpl extends ServiceImpl<SysMessageMapper, SysMessage>
        implements ISysMessageService {

    @Override
    public void sendMessage(SysMessage message) {
        message.setCreateTime(LocalDateTime.now());
        message.setReadStatus("0");
        message.setDelFlag("0");
        save(message);
    }

    @Override
    public Page<SysMessage> getUserMessages(Long userId, String type, Integer pageNum, Integer pageSize) {
        return lambdaQuery()
                .eq(SysMessage::getUserId, userId)
                .eq(type != null, SysMessage::getType, type)
                .eq(SysMessage::getDelFlag, "0")
                .orderByDesc(SysMessage::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
    }

    @Override
    public void markRead(Long messageId) {
        lambdaUpdate()
                .eq(SysMessage::getMessageId, messageId)
                .set(SysMessage::getReadStatus, "1")
                .set(SysMessage::getUpdateTime, LocalDateTime.now())
                .update();
    }

    @Override
    public void markAllRead(Long userId) {
        lambdaUpdate()
                .eq(SysMessage::getUserId, userId)
                .eq(SysMessage::getReadStatus, "0")
                .set(SysMessage::getReadStatus, "1")
                .set(SysMessage::getUpdateTime, LocalDateTime.now())
                .update();
    }

    @Override
    public void deleteMessage(Long messageId) {
        lambdaUpdate()
                .eq(SysMessage::getMessageId, messageId)
                .set(SysMessage::getDelFlag, "1")
                .set(SysMessage::getUpdateTime, LocalDateTime.now())
                .update();
    }

    @Override
    public Long getUnreadCount(Long userId) {
        return lambdaQuery()
                .eq(SysMessage::getUserId, userId)
                .eq(SysMessage::getReadStatus, "0")
                .eq(SysMessage::getDelFlag, "0")
                .count();
    }
}
